//
//  PhotoViewController.m
//  TestPhotoMS
//
//  Created by Hung Nguyen Thanh on 10/2/11.
//  Copyright (c) 2011 __MyCompanyName__. All rights reserved.
//

#import "PhotoViewController.h"
#import "UITableViewCellWithIconList.h"

@implementation PhotoViewController
@synthesize activityIndicatorView;
@synthesize photoTableView;
@synthesize segmentedControl;
@synthesize photoImageView;
@synthesize photo;
@synthesize delegate;
@synthesize listPhoto;
@synthesize numOfCell, numOfIconInCell;

- (IBAction)logout:(id)sender {
    [self dismissModalViewControllerAnimated:YES];
}

- (IBAction)camera:(id)sender {
    UIImagePickerController *imagePickerController = [[UIImagePickerController alloc] init];
    imagePickerController.delegate = self;
    imagePickerController.sourceType = UIImagePickerControllerSourceTypeCamera;
    [self presentModalViewController:imagePickerController animated:YES];
}

- (IBAction)modeLoadChange:(id)sender {
    UISegmentedControl *seg = (UISegmentedControl *)sender;
    if (seg.selectedSegmentIndex == 0) {
        [self loadPhotoFromServer:TOP_RATED];
    } else {
        [self loadPhotoFromServer:MY_PHOTO];
    }
}

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil photo:(Photo *)aPhoto
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        self.photo = aPhoto;
    }
    
    return self;
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    [segmentedControl setSelectedSegmentIndex:0];
    [self modeLoadChange:segmentedControl];
}

- (void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    photoImageView.image = photo.image;
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleTap:)];
    photoImageView.userInteractionEnabled = YES;
    [photoImageView addGestureRecognizer:tap];
}

- (void)viewDidUnload
{
    [self setPhotoImageView:nil];
    [self setActivityIndicatorView:nil];
    [self setPhotoTableView:nil];
    [self setSegmentedControl:nil];
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

- (void)handleTap:(UITapGestureRecognizer *)gestureRecognizer{
//    [self.navigationController popViewControllerAnimated:YES];
//    [self.navigationController pushViewController:self.parentViewController animated:YES];
    if ([delegate respondsToSelector:@selector(photoViewDidEnd:)]) {
        [delegate photoViewDidEnd:self];
    }
}

- (void)loadPhotoFromServer:(PhotoMode)mode{
    [activityIndicatorView startAnimating];
    XMLProcess *xmlProcess = [[XMLProcess alloc] init];
    xmlProcess.XMLDelegate = self;
    if (mode == TOP_RATED) {
        [xmlProcess performSelectorInBackground:@selector(parserXMLWithURL:) withObject:GET_PHOTO_TOP_RATE];
    } else {
        [xmlProcess performSelectorInBackground:@selector(parserXMLWithURL:) withObject:GET_PHOTO_BY_USER];
    }
}

- (void)loadIconFile{
    
    
    
}
- (void)haveGetNewImage:(Photo *)newPhoto{
    
}
- (void)getCompleteImage:(NSArray *)alistPhoto{
    [activityIndicatorView stopAnimating];
    self.listPhoto = [[NSMutableArray alloc] initWithArray:alistPhoto];
    
    CGFloat heightOfCell = 320.0f; // Height of cell in tableview
    CGFloat iconWidth = 90;
    numOfIconInCell = heightOfCell / (iconWidth + 10);
    numOfCell = ceilf([listPhoto count] / numOfIconInCell);
    if ([listPhoto count] % numOfIconInCell != 0) {
        numOfCell++;
    }
    
    NSLog(@"Total icon: %d, total cell: %d", [listPhoto count], numOfCell);
    
    [photoTableView performSelectorOnMainThread:@selector(reloadData) withObject:nil waitUntilDone:NO];
}

#pragma mark TableView
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return numOfCell;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    UITableViewCellWithIconList *cell = nil;
    static NSString *cellIdentifier = @"cellIdentifier";
    cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    if (cell == nil) {
        cell = [[UITableViewCellWithIconList alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier numOfIconInCell:numOfIconInCell];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.delegate = self;
    }
    cell.topIndex = indexPath.row;
    cell.listIcon = self.listPhoto;
    cell.numOfIconInCell = numOfIconInCell;
    [cell setupIcon]; 
    return cell;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 120;
}
#pragma mark -

#pragma mark ImagePickerControllerDelegate
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingImage:(UIImage *)image editingInfo:(NSDictionary *)editingInfo{
    [self uploadImage:image];
    [picker dismissModalViewControllerAnimated:YES];
}
#pragma mark -

#pragma mark Upload

- (void)uploadImage:(UIImage *)image{
//    NSMutableDictionary* post_dict = [[NSMutableDictionary alloc] initWithCapacity:2];
//    //    [post_dict setObject:@"test_value" forKey:@"test_key"];
//    [post_dict setObject:[NSURL fileURLWithPath:[[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"about.png"]] forKey:@"file1"];
    
    NSString *stringBoundary = [NSString stringWithString:@"0xKhTmLbOuNdArY"];
    NSMutableData *postBody = [NSMutableData data];
	[postBody appendData:[[NSString stringWithFormat:@"--%@\r\n",stringBoundary] dataUsingEncoding:NSUTF8StringEncoding]];
	// file field
	[postBody appendData:[[NSString stringWithString:@"Content-Disposition: form-data; name=\"files[]\"; filename=\"myImage.png\"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
	[postBody appendData:[[NSString stringWithString:@"Content-Type: application/octet-stream\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
	[postBody appendData:UIImageJPEGRepresentation(image, 1.0)];
	[postBody appendData:[[NSString stringWithFormat:@"\r\n--%@--\r\n",stringBoundary] dataUsingEncoding:NSUTF8StringEncoding]];
    
    NSMutableURLRequest* post = [NSMutableURLRequest requestWithURL: [NSURL URLWithString:UPLOAD_PHOTO]];
    
    NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@",stringBoundary];
    
    [post addValue: contentType forHTTPHeaderField: @"Content-Type"];
    [post setHTTPMethod: @"POST"];
    [post setHTTPBody:postBody];
    NSURLResponse* response;
    NSError* error;
    NSData* result = [NSURLConnection sendSynchronousRequest:post returningResponse:&response error:&error];
    
    NSLog(@"%@", [[NSString alloc] initWithData:result encoding:NSASCIIStringEncoding]);
    
}

- (NSData *)dataForPOSTWithDictionary:(NSDictionary *)aDictionary boundary:(NSString *)aBoundary {
    NSArray *myDictKeys = [aDictionary allKeys];
    NSMutableData *myData = [NSMutableData dataWithCapacity:1];
    NSString *myBoundary = [NSString stringWithFormat:@"%@\r\n", aBoundary];
    
    for(int i = 0;i < [myDictKeys count];i++) {
        id myValue = [aDictionary valueForKey:[myDictKeys objectAtIndex:i]];
        [myData appendData:[myBoundary dataUsingEncoding:NSUTF8StringEncoding]];
        //if ([myValue class] == [NSString class]) {
        if ([myValue isKindOfClass:[NSString class]]) {
            [myData appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"%@\"\r\n\r\n", [myDictKeys objectAtIndex:i]] dataUsingEncoding:NSUTF8StringEncoding]];
            [myData appendData:[[NSString stringWithFormat:@"%@", myValue] dataUsingEncoding:NSUTF8StringEncoding]];
        } else if(([myValue isKindOfClass:[NSURL class]]) && ([myValue isFileURL])) {
            [myData appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"%@\"; filename=\"%@\"\r\n", [myDictKeys objectAtIndex:i], [[myValue path] lastPathComponent]] dataUsingEncoding:NSUTF8StringEncoding]];
            [myData appendData:[[NSString stringWithFormat:@"Content-Type: application/octet-stream\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
            [myData appendData:[NSData dataWithContentsOfFile:[myValue path]]];
        } else if(([myValue isKindOfClass:[NSData class]])) {
            [myData appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"%@\"; filename=\"%@\"\r\n", [myDictKeys objectAtIndex:i], [myDictKeys objectAtIndex:i]] dataUsingEncoding:NSUTF8StringEncoding]];
            [myData appendData:[[NSString stringWithFormat:@"Content-Type: application/octet-stream\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
            [myData appendData:myValue];
        } // eof if()
        
        [myData appendData:[[NSString stringWithString:@"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
    } // eof for()
    [myData appendData:[[NSString stringWithFormat:@"--%@--\r\n", aBoundary] dataUsingEncoding:NSUTF8StringEncoding]];
    
    return myData;
}
#pragma mark -

#pragma mark Photo choise
- (void)didSelectedIcon:(Photo *)aphoto{
    NSLog(@"Photo: %@", aphoto.fileName);
}
#pragma mark -


@end
